import { useEffect, useState } from "react";
import DataDialog, { type DataDialogProps } from "./basic";
import Register from "./register";

type DataDialogProviderOptions = Omit<DataDialogProps, "open" | "onOpenChange">;

const channel = new Register<DataDialogProviderOptions>();

// eslint-disable-next-line react-refresh/only-export-components
export const openDialog = channel.open;

const DialogProvider: React.FC<{ id?: string }> = ({ id }) => {
  const [open, setOpen] = useState(false);
  const [options, setOptions] = useState<DataDialogProviderOptions>();
  const dialogProps = { ...(options ?? {}), title: options?.title ?? "" };

  useEffect(() => {
    channel.register({
      setOptions,
      setOpen,
    });
    return () => {
      channel.unregister(id);
    };
  }, [id]);

  return <DataDialog open={open} onOpenChange={setOpen} {...dialogProps} />;
};

export default DialogProvider;
